package com.itqf.filter;

import com.itqf.Util.JwtUtile.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ResourceBundle;

public class PermissionInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求地址
        String requestURI = request.getRequestURI();
        //2.判断是否是匿名地址(即用户不登录也可以访问的地址)
//        ResourceBundle aPublic = ResourceBundle.getBundle("url");

        System.out.println("requestURI=" + requestURI);
//        System.out.println("public="+aPublic);

        if (requestURI.contains("swagger-") || requestURI.contains("/loginpassword1") ||
                requestURI.contains("/m/loginpassword")||requestURI.contains("/usr/local/tomcat/apache-tomcat-8.5.34/webapps/ROOT/upload/"))
        {
            return true;
        }
        //.3.判断访问的地址是否被包含在配置文件中
//        if (aPublic.containsKey(requestURI))
//        {
//          return true;
//        }else
//        {
//            获取请求中的cookie
//            Cookie[] cookies = request.getCookies();
//
//            String cookName="token";

         String header = request.getHeader("x-access-token");
        if (header != null) {
            //4.校验token是否有效
            Claims claims = JwtUtils.checkToken(header);
            if (claims != null) {
                return true;
            } else {
//                           throw new DiyException("您的token码失效");
                return false;
            }
        }
//        }

        response.setHeader("x-access-token", "null");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}